#!/bin/bash

version=1.0.2

wget -O /tmp/FreeCAD.AppImage "https://github.com/FreeCAD/FreeCAD/releases/download/${version}/FreeCAD_${version}-conda-Linux-aarch64-py311.AppImage" || exit 1

sudo mv -f /tmp/FreeCAD.AppImage /opt/FreeCAD.AppImage || error "Failed to move AppImage to /opt"

status -n "Installing AppImage to /opt, making it executable, adding symlink... "
sudo chmod +x /opt/FreeCAD.AppImage || error "Failed to mark as executable!"
# Make terminal command
sudo rm -f /usr/local/bin/FreeCAD
sudo ln -s /opt/FreeCAD.AppImage /usr/local/bin/FreeCAD || error "Failed to make /usr/local/bin/FreeCAD terminal symlink!"
status_green Done


### EXTRACT OTHER ASSETS
status -n "Extracting assets... "
cd /tmp
rm -rf squashfs-root
/opt/FreeCAD.AppImage --appimage-extract usr/share/mime/packages/org.freecad.FreeCAD.xml || error "Failed to extract from appimage"
/opt/FreeCAD.AppImage --appimage-extract org.freecad.FreeCAD.svg || error "Failed to extract from appimage"
/opt/FreeCAD.AppImage --appimage-extract org.freecad.FreeCAD.desktop || error "Failed to extract from appimage"

sed -i 's/Exec=AppRun/Exec=FreeCAD/g' /tmp/squashfs-root/org.freecad.FreeCAD.desktop
sudo mv -f /tmp/squashfs-root/org.freecad.FreeCAD.desktop /usr/share/applications/org.freecad.FreeCAD.desktop || error 'Unable to move .desktop file from tmp'

sudo mv -f /tmp/squashfs-root/org.freecad.FreeCAD.svg /usr/share/pixmaps/org.freecad.FreeCAD.svg || error 'Failed to install the icon.'

sudo mkdir -p /usr/local/share/mime/packages
sudo mv -f /tmp/squashfs-root/usr/share/mime/packages/org.freecad.FreeCAD.xml /usr/local/share/mime/packages/org.freecad.FreeCAD.xml
rm -rf squashfs-root
cd

sudo update-mime-database /usr/local/share/mime
status_green Done

# Write mimetype association to ~/.config/mimeapps.list
if ! grep -qF 'org.freecad.FreeCAD.desktop' ~/.config/mimeapps.list; then
  status -n "Associating the .fcstd mimetype with FreeCAD... "
  if ! grep -qF '[Added Associations]' ~/.config/mimeapps.list; then
    echo "[Added Associations]" >> ~/.config/mimeapps.list
  fi
  echo "application/x-extension-fcstd=org.freecad.FreeCAD.desktop;" >> ~/.config/mimeapps.list
  status_green Done
fi

exit 0
